<template>
  <div class="template-card" :class="{ featured: featured }">
    <!-- 精选标识 -->
    <div v-if="template.featured && showFeaturedBadge" class="featured-badge">
      <el-icon><Star /></el-icon>
      精选
    </div>

    <!-- 模板头部 -->
    <div class="card-header">
      <div class="template-info">
        <h3 class="template-name">{{ template.name }}</h3>
        <p class="template-description">{{ template.description }}</p>
      </div>
      <div class="template-actions">
        <el-dropdown @command="handleCommand">
          <el-button type="text" size="small">
            <el-icon><MoreFilled /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="use">使用模板</el-dropdown-item>
              <el-dropdown-item command="favorite">
                {{ template.isFavorited ? '取消收藏' : '收藏' }}
              </el-dropdown-item>
              <el-dropdown-item command="share">分享</el-dropdown-item>
              <el-dropdown-item command="report">举报</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 模板标签 -->
    <div v-if="template.tags && template.tags.length > 0" class="template-tags">
      <el-tag
        v-for="tag in template.tags.slice(0, 3)"
        :key="tag"
        size="small"
        type="info"
      >
        {{ tag }}
      </el-tag>
      <el-tag v-if="template.tags.length > 3" size="small" type="info">
        +{{ template.tags.length - 3 }}
      </el-tag>
    </div>

    <!-- 软件列表 -->
    <div v-if="template.softwareList && template.softwareList.length > 0" class="template-software">
      <h4>包含软件 ({{ template.softwareList.length }})</h4>
      <div class="software-tags">
        <el-tag
          v-for="software in template.softwareList.slice(0, 3)"
          :key="software.id"
          size="small"
          type="info"
        >
          {{ software.displayName }}
        </el-tag>
        <el-tag
          v-if="template.softwareList.length > 3"
          size="small"
          type="info"
        >
          +{{ template.softwareList.length - 3 }}
        </el-tag>
      </div>
    </div>

    <!-- 模板分类 -->
    <div class="template-category">
      <el-tag :type="getCategoryType(template.category)" size="small">
        {{ getCategoryName(template.category) }}
      </el-tag>
    </div>

    <!-- 模板元信息 -->
    <div class="template-meta">
      <div class="meta-item">
        <el-icon><User /></el-icon>
        <span>{{ template.createdByNickname || template.createdBy || '匿名用户' }}</span>
      </div>
      <div class="meta-item">
        <el-icon><Download /></el-icon>
        <span>{{ template.downloadCount || 0 }} 次使用</span>
      </div>
      <div class="meta-item">
        <el-icon><Calendar /></el-icon>
        <span>{{ formatTime(template.createdAt) }}</span>
      </div>
    </div>

    <!-- 评分信息 -->
    <div v-if="template.rating || template.ratingCount" class="template-rating">
      <el-rate
        v-model="displayRating"
        disabled
        size="small"
        :max="5"
        :allow-half="true"
      />
      <span class="rating-text">
        {{ template.rating ? template.rating.toFixed(1) : '0.0' }}
        ({{ template.ratingCount || 0 }})
      </span>
    </div>



    <!-- 操作按钮 -->
    <div class="card-actions">
      <el-button
        type="primary"
        size="small"
        @click="$emit('use', template)"
      >
        <el-icon><Plus /></el-icon>
        使用模板
      </el-button>

      <el-button
        size="small"
        @click="$emit('preview', template)"
      >
        <el-icon><View /></el-icon>
        预览
      </el-button>

      <el-button
        :type="template.isFavorited ? 'warning' : 'default'"
        size="small"
        @click="$emit('favorite', template)"
      >
        <el-icon>
          <StarFilled v-if="template.isFavorited" />
          <Star v-else />
        </el-icon>
      </el-button>

      <el-dropdown @command="handleCommand" trigger="click">
        <el-button size="small">
          <el-icon><MoreFilled /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="rate">
              <el-icon><Star /></el-icon>
              评分
            </el-dropdown-item>
            <el-dropdown-item command="share">
              <el-icon><Share /></el-icon>
              分享
            </el-dropdown-item>
            <el-dropdown-item command="report">
              <el-icon><Warning /></el-icon>
              举报
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 评分弹窗 - 使用Teleport传送到body，避免受父组件影响 -->
    <Teleport to="body">
      <el-dialog
        v-model="showRatingDialog"
        title="为模板评分"
        width="400px"
        center
        :close-on-click-modal="false"
        :close-on-press-escape="!isRatingSubmitting"
        :z-index="3000"
        append-to-body
        destroy-on-close
      >
        <div class="rating-dialog" v-loading="isRatingSubmitting">
          <p>请为这个模板评分：</p>
          <el-rate
            v-model="userRating"
            :max="5"
            size="large"
            :disabled="isRatingSubmitting"
          />
          <p class="rating-tip">
            {{ isRatingSubmitting ? '正在提交评分...' : '选择星级后点击确认按钮' }}
          </p>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button
              @click="handleCancelRating"
              :disabled="isRatingSubmitting"
            >
              取消
            </el-button>
            <el-button
              type="primary"
              @click="handleConfirmRating"
              :disabled="isRatingSubmitting || userRating === 0"
            >
              确认评分
            </el-button>
          </div>
        </template>
      </el-dialog>
    </Teleport>
  </div>
</template>

<script setup>
import { ref, computed, Teleport } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Star,
  StarFilled,
  Download,
  View,
  Plus,
  MoreFilled,
  User,
  Calendar,
  Share,
  Warning
} from '@element-plus/icons-vue'
import { getCategoryName, getCategoryType } from '../constants/templateCategories'

const props = defineProps({
  template: {
    type: Object,
    required: true
  },
  featured: {
    type: Boolean,
    default: false
  },
  showFeaturedBadge: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['use', 'favorite', 'rate', 'preview'])

const userRating = ref(0)
const showRatingDialog = ref(false)
const isRatingSubmitting = ref(false)

// 添加一个标记来防止重复打开对话框
const isDialogOpening = ref(false)

const displayRating = computed(() => {
  return props.template.rating || 0
})

// 方法

const formatNumber = (num) => {
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
  if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
  if (diff < 2592000000) return Math.floor(diff / 86400000) + '天前'
  
  return date.toLocaleDateString()
}

const handleCommand = (command) => {
  // 使用nextTick确保下拉菜单完全关闭后再打开对话框
  switch (command) {
    case 'use':
      emit('use', props.template)
      break
    case 'favorite':
      emit('favorite', props.template)
      break
    case 'rate':
      // 防止重复打开对话框
      if (isDialogOpening.value || showRatingDialog.value) {
        return
      }

      isDialogOpening.value = true

      // 延迟打开对话框，确保下拉菜单完全关闭
      setTimeout(() => {
        userRating.value = 0
        isRatingSubmitting.value = false
        showRatingDialog.value = true
        isDialogOpening.value = false
      }, 150)
      break
    case 'share':
      handleShare()
      break
    case 'report':
      handleReport()
      break
  }
}

const handleConfirmRating = () => {
  // 防止重复提交或无效评分
  if (isRatingSubmitting.value || userRating.value <= 0) {
    return
  }

  // 设置提交状态
  isRatingSubmitting.value = true

  // 提交评分
  emit('rate', props.template, userRating.value)

  // 延迟关闭对话框，给后端请求足够时间
  setTimeout(() => {
    userRating.value = 0
    showRatingDialog.value = false
    isRatingSubmitting.value = false
    isDialogOpening.value = false
  }, 1500)
}

const handleCancelRating = () => {
  // 重置所有状态并关闭对话框
  userRating.value = 0
  showRatingDialog.value = false
  isRatingSubmitting.value = false
  isDialogOpening.value = false
}

const handleShare = () => {
  const url = `${window.location.origin}/templates/${props.template.id}`
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('模板链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制链接')
  })
}

const handleReport = () => {
  ElMessage.info('举报功能开发中...')
}
</script>

<style scoped>
.template-card {
  background: white;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  padding: 20px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.template-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  transform: translateY(-2px);
}

.template-card.featured {
  border-color: #f56c6c;
  background: linear-gradient(135deg, #fff 0%, #fef9f9 100%);
}

.featured-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: linear-gradient(135deg, #f56c6c, #ff8a8a);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.template-info {
  flex: 1;
}

.template-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.template-description {
  font-size: 14px;
  color: #606266;
  margin: 0;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.template-tags {
  margin-bottom: 12px;
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.template-software {
  margin-bottom: 16px;
}

.template-software h4 {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.software-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.template-category {
  margin-bottom: 16px;
}

.template-meta {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #606266;
}

.meta-item .el-icon {
  font-size: 14px;
  color: #909399;
}

.template-rating {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.rating-text {
  font-size: 13px;
  color: #606266;
}

.template-stats {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
  font-size: 14px;
  color: #909399;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.rating-text {
  font-size: 12px;
  margin-left: 4px;
}

.creator-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding: 8px 0;
  border-top: 1px solid #f5f7fa;
}

.creator-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.creator-name {
  font-size: 13px;
  font-weight: 500;
  color: #303133;
}

.create-time {
  font-size: 12px;
  color: #909399;
}

.card-actions {
  display: flex;
  gap: 6px;
  align-items: center;
  flex-wrap: wrap;
}

.card-actions .el-button {
  flex: 0 0 auto;
  min-width: 0;
}

.card-actions .el-button:first-child {
  flex: 1;
  min-width: 80px;
}

.rating-popup {
  text-align: center;
}

.rating-dialog {
  text-align: center;
  padding: 20px 0;
  min-height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.rating-dialog p {
  margin: 0 0 16px 0;
  color: #606266;
  font-size: 14px;
}

.rating-tip {
  margin: 16px 0 0 0;
  font-size: 12px;
  color: #909399;
  transition: color 0.3s ease;
}

/* 评分组件样式优化 */
.rating-dialog .el-rate {
  margin: 8px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.rating-dialog .el-rate__item {
  margin-right: 8px;
}

/* 加载状态样式 */
.rating-dialog.el-loading-parent--relative {
  min-height: 120px;
}

/* 确保评分对话框在全局层级显示，不受模板卡片影响 */
:deep(.el-dialog__wrapper) {
  z-index: 3000 !important;
}

/* 防止模板卡片的hover效果影响对话框 */
.template-card:has(.el-dialog__wrapper) {
  transform: none !important;
}

/* 确保对话框遮罩层正确显示 */
:deep(.el-overlay) {
  z-index: 2999 !important;
}

@media (max-width: 768px) {
  .template-card {
    padding: 16px;
  }
  
  .template-stats {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .card-actions {
    flex-direction: column;
  }
  
  .card-actions .el-button {
    width: 100%;
  }
}
</style>
